<script setup>
import InputText from "../components/InputText.vue";
import InputSelect from "../components/InputSelect.vue";
import Button from "../components/Button.vue";
import TextDivider from "../components/TextDivider.vue";
import DataTable from "../components/DataTable.vue";
import Textarea from "../components/Textarea.vue";
import InputDate from "../components/InputDate.vue";
import IconSvg from "../components/IconSvg.vue";
import Model from "../components/Model.vue"
import PaginationBasic from "../components/PaginationBasic.vue";
import Message from "../components/Message/Message.js";
import { ref, onMounted, reactive } from "vue"
import axios from "../axios/axios.js";
const searchInfo = ref({ name: '' });
const addInfo = ref({ taskcode: "", taskname: '', processid: 0, quantity: 0, producetype: 0, planstartat: "", planendat: "", stampingpartid: 0, moldid: 0, remark: "" })
const pageData = ref({
  currentPage: 1,
  total: 0,
  pageSize: 10,
})
const devicePageData = ref({
  currentPage: 1,
  total: 0,
  pageSize: 10,
})
const logPageData = ref({
  currentPage: 1,
  total: 0,
  pageSize: 10,
})
const tableData = ref()
const deviceTableData = ref([])
const logTableData = ref([])
const processid = ref()
const isOperate = ref(false)
const isAdd = ref(false)
const processOptions = ref([])
const showCodeModel = ref(false)
const codeInfoList = ref([])
const defaultIds = ref([])
const isStamping = ref(true)
const showDetail = ref(false)
const taskDevice = ref([])
// 列配置
const tableColumns = [
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'taskname', title: '任务名称', dataIndex: 'taskname' },
  { key: 'processname', title: '工艺名称', dataIndex: 'processname' },
  { key: 'identificationcode', title: '标识', dataIndex: 'identificationcode' },
  { key: 'quantity', title: '数量', dataIndex: 'quantity' },
  { key: 'status', title: '状态', dataIndex: 'status' },
  { key: 'createTime', title: '创建时间', dataIndex: 'createtime' },
  { key: 'action', title: '操作', dataIndex: 'action' },
]

const deviceTableColumns = [
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'devicename', title: '名称', dataIndex: 'devicename' },
  { key: 'identify', title: '标识', dataIndex: 'identify' },
  { key: 'type', title: '类型', dataIndex: 'type' },
  { key: 'quantity', title: '数量', dataIndex: 'quantity' }
]
const logTableColumns = [
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'logtime', title: '时间', dataIndex: 'logtime' },
  { key: 'logcontent', title: '内容', dataIndex: 'logcontent' },
  { key: 'identificationcode', title: '标识', dataIndex: 'identificationcode' },
]
// 页码变化时触发
const handlePageChange = (page) => {
  pageData.value.currentPage = page
  // 这里可以调用接口加载对应页的数据
  getData()
}
const handleDevicePageChange = (page) => {
  devicePageData.value.currentPage = page
  // 这里可以调用接口加载对应页的数据
  getDeviceData()
}
const handleLogPageChange = (page) => {
  logPageData.value.currentPage = page
  getLogData()
}
const handleUpdate = (item) => {
  isOperate.value = true
  isStamping.value = true
  getProcess()
  getDeviceData()
  addInfo.value = {
    ...item
  }
  defaultIds.value = [item.stampingpartid]

}
const openAddModel = () => {
  isOperate.value = true
  isAdd.value = true
  isStamping.value = true
  //获取编号
  getSerialNumber()
  getProcess()
  getDeviceData()
}
const handleConfirm = () => {
  if (!addInfo.value.taskname || addInfo.value.taskname.trim() === "") {
    Message.warn('请输入任务名称');
    return;
  }
  if (!addInfo.value.taskcode || addInfo.value.taskcode.trim() === "") {
    Message.warn('请输入订单编号');
    return;
  }
  if (addInfo.value.type == 0) {
    Message.warn('请选择生产类型');
    return;
  }
  if (!addInfo.value.quantity || addInfo.value.quantity <= 0) {
    Message.warn('请输入有效的数量');
    return;
  }
  if (!addInfo.value.planstartat || addInfo.value.planstartat.trim() === "") {
    Message.warn('请选择计划开始时间');
    return;
  }
  if (!addInfo.value.planendat || addInfo.value.planendat.trim() === "") {
    Message.warn('请选择计划完成时间');
    return;
  }
  if (addInfo.value.planendat < addInfo.value.planstartat) {
    Message.warn('计划完成时间不能早于计划开始时间');
    return;
  }
  if (addInfo.value.processid == 0) {
    Message.warn('请选择工艺路线');
    return;
  }
  if (!addInfo.value.stampingpartid || addInfo.value.stampingpartid == 0) {
    Message.warn('请选择冲压件物料');
    return;
  }
  if (!addInfo.value.moldid || addInfo.value.moldid == 0) {
    Message.warn('请选择模具物料');
    return;
  }

  // 构建任务提交数据（根据任务管理场景调整参数）
  const submitData = {
    "taskname": addInfo.value.taskname,
    "taskcode": addInfo.value.taskcode,
    "producetype": addInfo.value.producetype,
    "planstartat": addInfo.value.planstartat,
    "planendat": addInfo.value.planendat,
    "processid": addInfo.value.processid,
    "quantity": addInfo.value.quantity,
    "stampingpartid": addInfo.value.stampingpartid,
    "moldid": addInfo.value.moldid,
    "remark": addInfo.value.remark
  };
  console.log(addInfo.value.stampingpartid, addInfo.value, submitData);
  if (isAdd.value) {
    // 调用任务保存接口
    axios.post("/api/task/save", submitData)
      .then(res => {
        if (res.data.Code === "200") {
          Message.success('任务添加成功');
          isOperate.value = false;
          isAdd.value = false;
          addInfo.value = { taskcode: "", taskname: '', processid: 0, quantity: 0, producetype: 0, planStartAt: "", planEndAt: "", stampingpartid: 0, moldid: 0, remark: "" };
          getData(); // 刷新任务列表
        } else {
          Message.warn(res.data.Msg);
        }
      })
      .catch(err => {
        Message.error('网络错误，添加任务失败');
        console.error(err);
      });
  } else {
    // 调用任务保存接口
    axios.post("/api/task/update", { id: addInfo.value.id, ...submitData })
      .then(res => {
        if (res.data.Code === "200") {
          Message.success('任务修改成功');
          isOperate.value = false;
          addInfo.value = { taskcode: "", taskname: '', processid: 0, quantity: 0, producetype: 0, planStartAt: "", planEndAt: "", stampingpartid: 0, moldid: 0, remark: "" };
          getData(); // 刷新任务列表
        } else {
          Message.warn(res.data.Msg);
        }
      })
      .catch(err => {
        Message.error('网络错误，添加任务失败');
        console.error(err);
      });
  }

};
const handleCancel = () => {
  isOperate.value = false
  isAdd.value = false
  addInfo.value = { taskcode: "", taskname: '', processid: 0, quantity: 0, producetype: 0, planStartAt: "", planEndAt: "", stampingpartid: 0, moldid: 0, remark: "" }
}

const resetSearch = () => {
  searchInfo.value = { name: '' }
  getData()
}
const handleSelectChange = (selectedIds) => {
  if (isStamping.value) {
    console.log(selectedIds, deviceTableData.value, deviceTableData.value.length);

    if (selectedIds.length != 0 && deviceTableData.value.length != 0) {
      var data = deviceTableData.value.find(item => item.id == selectedIds[0])
      addInfo.value.quantity = data.quantity
    }
    if (selectedIds.length != 0) {
      addInfo.value.stampingpartid = selectedIds[0]
    }

  } else {
    if (selectedIds.length != 0) {
      addInfo.value.moldid = selectedIds[0]
    }
  }
}
const handleday = (item) => {
  getTaskDetail(item.id)
  showDetail.value = true
  getLogData(item.id)
}
const getLogData = (id) => {
  axios.get("/api/log/select?taskId=" + id).then(res => {
    if (res.data.Code == "200") {
      logTableData.value = res.data.Data.records
    } else {
      Message.error(res.data.Msg)

    }
  })
}
const getTaskDetail = (id) => {
  axios.get("/api/task/detail?taskId=" + id).then(res => {
    if (res.data.Code == "200") {
      taskDevice.value = res.data.Data
    } else {
      Message.error(res.data.Msg)
    }
  })
}
const handleCode = (id) => {
  var data = deviceTableData.value.find(item => item.id === id)
  codeInfoList.value = data.identificationlist.split(",")
  showCodeModel.value = true
}
const getDeviceData = () => {
  var type = isStamping.value ? "冲压件" : "模具"
  var url = '/api/codingdevice/material?type=' + type + "&pageNum=" + devicePageData.value.currentPage + "&pageSize=" + devicePageData.value.pageSize
  if (!isAdd.value) {
    if (isStamping.value) {
      url = url + "&id=" + addInfo.value.stampingpartid
    }
    url = url + "&id=" + addInfo.value.moldid
  }
  axios.get('/api/codingdevice/material?type=' + type + "&pageNum=" + devicePageData.value.currentPage + "&pageSize=" + devicePageData.value.pageSize)
    .then(res => {
      if (res.data.Code === "200") {
        deviceTableData.value = res.data.Data.records
        devicePageData.value = {
          ...devicePageData.value,
          total: res.data.Data.total || 0,
          pageSize: res.data.Data.size || 10,
        };
      } else {
        Message.warn(res.data.Msg);
      }
    })
    .catch(err => {
      Message.error('网络错误，获取设备列表失败');
    })
}
const getSerialNumber = () => {
  axios.get('/api/task/number')
    .then(res => {
      if (res.data.Code === "200") {
        addInfo.value.taskcode = res.data.Data
      } else {
        Message.warn(res.data.Msg || '获取编号失败');
      }
    })
    .catch(err => {
      Message.error('网络错误，获取编号失败');
    })
}
const getProcess = () => {
  var url = '/api/process/selectall'
  axios.get(url).then(res => {
    var procedures = []
    res.data.Data.forEach(element => {
      procedures.push({ label: element.processname, value: element.id })
    });
    processOptions.value = procedures
  })
}
const handleDelete = (item) => {
  // 确认删除对话框，使用任务名称替代设备名称
  if (window.confirm(`确定要删除任务"${item.taskname}"吗？此操作不可撤销！`)) {
    axios.get(`/api/task/delete?id=${item.id}`)
      .then(res => {
        if (res.data.Code === "200") {
          Message.success('任务删除成功');
          getData(); // 刷新任务列表
        } else {
          Message.warn(res.data.Msg || '删除失败');
        }
      })
      .catch(err => {
        Message.error('删除失败，请重试');
        console.error('删除任务错误：', err); // 修改错误提示文本
      });
  }
};
// 开始生产操作
const handleProduce = (item, status) => {
  var confirmMsg = ""
  var msg = ""
  if (status == 1) {
    confirmMsg = `确定要开始任务"${item.taskname}"的生产吗？`
    msg = "开始"
  } else {
    confirmMsg = `确定要暂停任务"${item.taskname}"的生产吗？`
    msg = "暂停"
  }
  console.log({
    id: item.id,  // 传递任务ID
    status: status
  });

  // 确认开始生产对话框
  if (window.confirm(confirmMsg)) {
    axios.post('/api/task/produce', {
      id: item.id,  // 传递任务ID
      status: status
    })
      .then(res => {
        if (res.data.Code === "200") {
          Message.success('生产已' + msg);
          getData(); // 刷新任务列表
        } else {
          Message.warn(res.data.Msg || msg + '生产失败');
        }
      })
      .catch(err => {
        Message.error('网络错误，无法生产' + msg);
        console.error(msg + '生产错误：', err);
      });
  }
};
const codeShow = (value) => {
  showCodeModel.value = true
  codeInfoList.value = value.identificationlist.split(",")
}

const getData = () => {
  let url = `/api/task/select?pageNum=${pageData.value.currentPage}&pageSize=${pageData.value.pageSize}`;

  // 拼接搜索参数
  if (searchInfo.value.name.trim()) {
    url += `&name=${encodeURIComponent(searchInfo.value.name)}`;
  }
  axios.get(url)
    .then(res => {
      if (res.data.Code === "200") {
        tableData.value = res.data.Data.records || [];
        pageData.value = {
          ...pageData.value,
          total: res.data.Data.total || 0,
          pageSize: res.data.Data.size || 10,
        };
      } else {
        Message.warn(res.data.Msg || '获取任务列表失败');
        tableData.value = [];
        pageData.value.total = 0;
      }
    })
    .catch(err => {
      Message.error('网络错误，无法获取任务列表');
      console.error(err);
    });
};

onMounted(() => {
  getData()
});
</script>
<template>
  <div class="bg-[white] w-full h-full pt-[40px] px-[40px] text-base flex flex-col">
    <div v-if="!isOperate && !showDetail" class="w-full h-full flex flex-col">
      <div class="flex justify-start items-center">
        <InputText type="text" label="名称" placeholder="请输入名称" class="w-[260px] mr-[20px]" v-model="searchInfo.name" />
        <Button type="primary" content="查询" class="mr-[20px]" @click="getData">
          <template #icon>
            <IconSvg name="search" class="w-[18px] h-[18px]"></IconSvg>
          </template>
        </Button>
        <Button content="重置" class="mr-[20px]" @click="resetSearch">
          <template #icon>
            <IconSvg name="refresh" class="w-[15px] h-[15px]"></IconSvg>
          </template>
        </Button>
      </div>
      <div class="mt-[40px] flex-1 overflow-auto">
        <div class="flex justify-start items-center">
          <Button type="primary" content="新增" class="mr-[20px]" @click="openAddModel" v-perm="'task:add'">
            <template #icon>
              <IconSvg name="add" class="w-[18px] h-[18px]"></IconSvg>
            </template>
          </Button>
        </div>

        <DataTable :dataSource="tableData" :columns="tableColumns" class="mt-[20px]">
          <template #status="{ item }">
            <span :class="{
              'text-gray-500': item.status === 0,
              'text-green-500': item.status === 1,
              'text-red-500': item.status === 2,
              'text-orange-500': !([0, 1, 2].includes(item.status))
            }">
              {{
                { 0: '待产', 1: '正在生产', 2: '暂停生产' }[item.status] || '未知状态'
              }}
            </span>
          </template>
          <template #action="{ item }">
            <a @click="handleProduce(item, 1)" class="mr-2 text-blue-500 cursor-pointer" v-if="item.status != 1"
              v-perm="'task:produce'">开始生产</a>
            <a @click="handleProduce(item, 2)" class="mr-2 text-blue-500 cursor-pointer" v-if="item.status == 1"
              v-perm="'task:produce'">停止生产</a>
            <a @click="handleUpdate(item)" class="mr-2 text-blue-500 cursor-pointer" v-if="item.status == 0">编辑</a>
            <a @click="handleDelete(item)" class="mr-2 text-red-500 cursor-pointer" v-if="item.status == 0">删除</a>
            <a @click="handleday(item)" class="text-blue-500 cursor-pointer">日志</a>
          </template>
        </DataTable>

      </div>
      <div class="flex justify-end items-center my-4" v-if="pageData.total > 0">
        <label class="font-medium">共{{ pageData.total }}条</label>
        <PaginationBasic :total="pageData.total" :page-size="pageData.pageSize" v-model:current="pageData.currentPage"
          @onPageChange="handlePageChange" />
      </div>
    </div>

    <!-- 添加任务 -->
    <div class="flex flex-col w-full h-full" v-if="isOperate">
      <div class="flex justify-end items-center">
        <div class="text-[18px] font-medium flex-1">添加任务订单</div>
      </div>
      <div class="overflow-auto flex-1">
        <div class="pt-6 space-y-8">
          <TextDivider text="基本信息" lineStyle="dashed" lineColor="black" align="left" leftOffset="50px"
            text-color="black" />
        </div>
        <div class="flex justify-start flex-wrap">
          <InputText type="text" label="订单编号" placeholder="请输入订单编号" class="w-[400px] my-4 mr-4" :required="true"
            label-width="80px" align="top" v-model="addInfo.taskcode" :disabled="true" />
          <InputText type="text" label="订单名称" placeholder="请输入订单名称" class="w-[400px] my-4 mr-4" :required="true"
            label-width="80px" align="top" v-model="addInfo.taskname" />
          <InputSelect label="生产类型" placeholder="请输入生产类型" class="w-[400px] my-4 mr-4" :required="true"
            label-width="80px" align="top" v-model="addInfo.producetype">
            <option value=0>零件加工生产</option>
            <option value=1>成品直接生产</option>
          </InputSelect>
        </div>
        <div class="pt-6 space-y-8">
          <TextDivider text="详细信息" lineStyle="dashed" lineColor="black" align="left" leftOffset="50px"
            text-color="black" />
        </div>
        <div class="flex justify-start flex-wrap">
          <InputText type="number" label="计划生产数量" placeholder="请输入生产数量" class="w-[400px] my-4 mr-4" :required="true"
            label-width="100px" align="top" v-model="addInfo.quantity" :disabled="true" />

          <InputDate label="计划开工时间" placeholder="请选择时间" class="w-[400px] my-4 mr-4" :required="true" label-width="100px"
            align="top" v-model="addInfo.planstartat"></InputDate>
          <InputDate label="计划完工时间" placeholder="请选择时间" class="w-[400px] my-4 mr-4" :required="true" label-width="100px"
            align="top" v-model="addInfo.planendat"></InputDate>
          <InputSelect label="工艺路线" placeholder="请输入工艺路线" class="w-[400px] my-4 mr-4" :required="true"
            label-width="100px" align="top" v-model="addInfo.processid">
            <option v-for="process in processOptions" :value="process.value">{{ process.label }}</option>
          </InputSelect>

        </div>
        <Textarea label="订单备注" placeholder="请输入备注" class="my-4" label-width="100px" align="top"
          v-model="addInfo.remark"></Textarea>
        <div class="pt-6 space-y-8">
          <TextDivider text="物料清单" lineStyle="dashed" lineColor="black" align="left" leftOffset="50px"
            text-color="black" />
        </div>
        <div class="border-b border-gray-200 mb-6">
          <button class="px-4 py-2 mr-2 font-medium border-b-2 transition-all"
            :class="isStamping ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'"
            @click="() => {
              deviceTableData = []
              isStamping = true
              defaultIds = [];
              getDeviceData();
              defaultIds = addInfo.stampingpartid == 0 ? [] : [addInfo.stampingpartid];
            }">
            冲压件
          </button>
          <button class="px-4 py-2 font-medium border-b-2 transition-all"
            :class="!isStamping ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700'"
            @click="() => {
              deviceTableData = []
              isStamping = false
              defaultIds = [];
              getDeviceData();
              defaultIds = addInfo.moldid == 0 ? [] : [addInfo.moldid];
            }">
            模具
          </button>
        </div>
        <DataTable :dataSource="deviceTableData" :columns="deviceTableColumns" class="mt-[20px]" :showCheckbox="true"
          @update:selectedIds="handleSelectChange" :default-selected-ids="defaultIds" :is-single-select="true">
          <template #identify="{ item }">
            <a @click="handleCode(item.id)" class="text-[#165dff] cursor-pointer">查看</a>
          </template>
        </DataTable>
        <div class="flex justify-end items-center my-4" v-if="devicePageData.total > 0">
          <label class="font-medium">共{{ devicePageData.total }}条</label>
          <PaginationBasic :total="devicePageData.total" :page-size="devicePageData.pageSize"
            v-model:current="devicePageData.currentPage" @onPageChange="handleDevicePageChange" />
        </div>
      </div>
      <div class="flex justify-end items-center my-4">
        <Button content="取消" @click="handleCancel" class="mr-4"></Button>
        <Button type="primary" content="确定" @click="handleConfirm"></Button>
      </div>

    </div>
    <!-- 详情 -->
    <div v-if="showDetail">
      <div class="flex justify-end items-center">
        <div class="text-[18px] font-medium flex-1">任务详情</div>
        <div>
          <Button content="返回" @click="showDetail = false"></Button>
        </div>
      </div>
      <div class="flex items-center mt-6">
        <div class="flex-1 border-solid border-[#a5a5a5] border-l-[1px] px-[10px]" v-for="value in taskDevice.device">
          <div class="flex justify-center items-center mb-4">
            <div class="w-[80px]">设备名称：</div>
            <div class="flex-1">{{ value.devicename }}</div>
          </div>
          <div class="flex justify-center items-center my-4">
            <div class="w-[80px]">使用标识：</div>
            <div class="flex-1">{{ value.useidentificationname }}</div>
          </div>
          <div class="flex justify-center items-center my-4">
            <div class="w-[80px]">所在仓位：</div>
            <div class="flex-1">{{ value.positionname }}</div>
          </div>
          <div class="flex justify-center items-center my-4">
            <div class="w-[80px]">数量：</div>
            <div class="flex-1">{{ value.useidentificationname }}</div>
          </div>
          <div class="flex justify-center items-center my-4">
            <div class="w-[80px]">创建时间：</div>
            <div class="flex-1">{{ value.createtime }}</div>
          </div>
          <div class="flex justify-center items-center my-4">
            <div class="w-[80px]">标识查看：</div>
            <div class="flex-1"><a class="text-[#165dff] cursor-pointer" @click="codeShow(value)">查看</a></div>
          </div>
          <div class="flex justify-center items-center my-4" v-perm="'code:download'">
            <div class="w-[80px]">标识下载：</div>
            <div class="flex-1"><a class="text-[#165dff] cursor-pointer">下载</a></div>
          </div>
        </div>
        <div class="flex-1 border-solid border-[#a5a5a5] border-l-[1px] px-[10px]" v-for="value in taskDevice.position">
          <div class="flex justify-center items-center mb-4">
            <div class="w-[80px]">仓位名称：</div>
            <div class="flex-1">{{ value.positionname }}</div>
          </div>
          <div class="flex justify-center items-center my-4">
            <div class="w-[80px]">使用标识：</div>
            <div class="flex-1">{{ value.useidentificationname }}</div>
          </div>
          <div class="flex justify-center items-center my-4">
            <div class="w-[80px]">创建时间：</div>
            <div class="flex-1">{{ value.createtime }}</div>
          </div>
          <div class="flex justify-center items-center my-4">
            <div class="w-[80px]">标识：</div>
            <div class="flex-1 text-wrap break-all">{{ value.identificationcode + "," +
              value.identificationcode }}</div>
          </div>
          <div class="flex justify-center items-center my-4" v-perm="'code:download'">
            <div class="w-[80px]">标识下载：</div>
            <div class="flex-1"><a class="text-[#165dff] cursor-pointer">下载</a></div>
          </div>
        </div>
      </div>
      <div class="mt-6">
        <DataTable :dataSource="logTableData" :columns="logTableColumns">

        </DataTable>
      </div>
      <div class="flex justify-end items-center my-4" v-if="logPageData.total > 0">
        <label class="font-medium">共{{ logPageData.total }}条</label>
        <PaginationBasic :total="logPageData.total" :page-size="logPageData.pageSize"
          v-model:current="logPageData.currentPage" @onPageChange="handleLogPageChange" />
      </div>
    </div>
    <Model :show="showCodeModel" @close="showCodeModel = false">
      <template #header>
        <h3>标识详情</h3>
      </template>
      <template #body>
        <div class="p-4 max-h-[500px] overflow-auto-y-auto">
          <!-- 按逗号分割后遍历显示 -->
          <div v-for="(code, index) in codeInfoList" :key="index" class="mb-1 break-all">
            {{ code }}
          </div>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-around">
          <Button content="关闭" @click="showCodeModel = false"></Button>
        </div>
      </template>
    </Model>
  </div>
</template>

<style scoped></style>
